# -*- coding: utf-8 -*-
"""
-------------------------------------------------
   File Name：     pre.py
   Description :
   Author :       liaozhaoyan
   date：          2023/7/31
-------------------------------------------------
   Change Activity:
                   2023/7/31:
-------------------------------------------------
"""
__author__ = 'liaozhaoyan'

from .base import DiagnosisJob, DiagnosisPreProcessor, DiagnosisTask, FileItem
import re

def checkNum(s):
    try:
        num = int(s, 10)
    except ValueError:
        return False
    if num <= 0:
        return False
    return True

def checkPids(s):
    pids = s.split(",")
    for pid in pids:
        if not checkNum(pid):
            return False
    return True

class PreProcessor(DiagnosisPreProcessor):
    """Get release info diagnosis

    Just invoke command in target instance and get stdout result

    Args:
        DiagnosisPreProcessor (_type_): _description_
    """

    def get_diagnosis_cmds(self, params: dict) -> DiagnosisTask:
        # 从前端传递的参数中读取目标实例IP
        instance = params.get("instance", "")
        cmd = "sysak java_collect "
        nums = params.get("nums", "")

        if len(nums) > 0:
            if checkNum(nums):
                cmd += "-t %s " % (nums)
            else:
                raise Exception("top nums illegal.")
        else:
            pids = params.get("pids", "")
            if checkPids(pids):
                cmd += "-p %s " % (pids)
            else:
                raise Exception("pids format illegal.")

        g = params.get("global", "on")
        if g == "on":
            cmd += "-b --zip"
        else:
            cmd += "--zip"

        # cmd = "/usr/local/sysak/.sysak_components/tools/java_collect -t %s -b --zip" % nums
        return DiagnosisTask(
            jobs=[
                # 在 instance 上执行 java_collect 命令
                # 并在命令执行结束后，拉取节点端的 /var/sysak/j_out.zip 文件到本地
                DiagnosisJob(instance=instance, cmd=cmd, fetch_file_list=[
                    FileItem("j_out.zip", remote_path="/var/sysak/j_out.zip")
                ])
            ]
        )

